<template>
  <div class="title-application">
    <el-card v-if="!hasApplied || applicationStatus === '未通过'">
      <template #header>
        <div class="card-header">
          <span>职称评审申请</span>
        </div>
      </template>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" enctype="multipart/form-data">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="目前职称" prop="currentTitle">
          <el-input v-model="form.currentTitle" />
        </el-form-item>
        <el-form-item label="申请职称" prop="applyTitle">
          <el-input v-model="form.applyTitle" />
        </el-form-item>
        <el-form-item label="院系" prop="department">
          <el-input v-model="form.department" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" />
        </el-form-item>
        <el-form-item label="申请材料" prop="attachment">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :show-file-list="true"
            :limit="1"
            :auto-upload="true"
            :file-list="fileList"
            :headers="uploadHeaders"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">文件大小不超过50MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交申请</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-if="applicationStatus === '未通过' && lastReason" :title="'上次申请未通过，原因：' + lastReason" type="error" show-icon />
    </el-card>
    <el-card v-else>
      <template #header>
        <div class="card-header">
          <span>职称评审申请状态</span>
        </div>
      </template>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="申请职称">{{ application.applyTitle }}</el-descriptions-item>
        <el-descriptions-item label="院系">{{ application.department }}</el-descriptions-item>
        <el-descriptions-item label="职位">{{ application.position }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(application.status)">{{ application.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ application.createTime }}</el-descriptions-item>
        <el-descriptions-item label="材料">
          <a v-if="application.attachment" :href="getAttachmentUrl(application.attachment)" target="_blank">下载附件</a>
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="application.status === '未通过'" label="未通过原因">{{ application.reason }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'TitleApplication',
  setup() {
    const form = reactive({
      name: '',
      gender: '',
      currentTitle: '',
      applyTitle: '',
      department: '',
      position: '',
      attachment: ''
    })
    const rules = {
      name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
      gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
      currentTitle: [{ required: true, message: '请输入目前职称', trigger: 'blur' }],
      applyTitle: [{ required: true, message: '请输入申请职称', trigger: 'blur' }],
      department: [{ required: true, message: '请输入院系', trigger: 'blur' }],
      position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
      attachment: [{ required: true, message: '请上传申请材料', trigger: 'change' }]
    }
    const formRef = ref(null)
    const fileList = ref([])
    const uploadUrl = '/api/upload' // 需后端支持通用上传接口
    const uploadHeaders = { Authorization: localStorage.getItem('token') }
    const application = ref(null)
    const hasApplied = ref(false)
    const applicationStatus = ref('')
    const lastReason = ref('')

    // 获取当前用户ID（假设已登录并存储在localStorage）
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const teacherId = userInfo.id ? Number(userInfo.id) : null

    // 查询自己申请
    const fetchMyApplication = async () => {
      if (!teacherId) {
        ElMessage.error('未获取到教师ID，请重新登录')
        return
      }
      const res = await axios.get('/api/users/me/title/my-applications', {
        params: { teacherId },
        headers: { Authorization: localStorage.getItem('token') }
      })
      if (res.data && res.data.length > 0) {
        application.value = res.data[0]
        hasApplied.value = true
        applicationStatus.value = application.value.status
        if (application.value.status === '未通过') {
          lastReason.value = application.value.reason
        }
      } else {
        hasApplied.value = false
      }
    }

    onMounted(() => {
      fetchMyApplication()
    })

    const handleUploadSuccess = (response) => {
      if (response && response.url) {
        form.attachment = response.url
        ElMessage.success('上传成功')
      } else {
        ElMessage.error('上传失败')
      }
    }
    const beforeUpload = (file) => {
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        ElMessage.error('文件大小不能超过50MB!')
      }
      return isLt50M
    }
    const submitForm = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          if (!teacherId) {
            ElMessage.error('未获取到教师ID，请重新登录')
            return
          }
          const payload = { ...form, teacherId }
          const res = await axios.post('/api/users/me/title/apply', payload, {
            headers: { Authorization: localStorage.getItem('token') }
          })
          if (res.data && res.data.includes('成功')) {
            ElMessage.success('提交成功')
            fetchMyApplication()
          } else {
            ElMessage.error(res.data || '提交失败')
          }
        }
      })
    }
    const getStatusType = (status) => {
      if (status === '审批中') return 'info'
      if (status === '已通过') return 'success'
      if (status === '未通过') return 'danger'
      return ''
    }
    const getAttachmentUrl = (url) => {
      if (!url) return ''
      // 从/uploads/xxx格式中提取文件名
      let fileName = url
      if (url.startsWith('/uploads/')) {
        fileName = url.substring(9) // 去掉'/uploads/'前缀
      }
      // 使用下载接口
      return `/api/title-attachment/${fileName}`
    }
    return {
      form,
      rules,
      formRef,
      fileList,
      uploadUrl,
      uploadHeaders,
      handleUploadSuccess,
      beforeUpload,
      submitForm,
      hasApplied,
      application,
      applicationStatus,
      lastReason,
      getStatusType,
      getAttachmentUrl
    }
  }
}
</script>

<style scoped>
.title-application {
  max-width: 600px;
  margin: 0 auto;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style> 